#include "bidwindow.h"
#include "ui_bidwindow.h"
#include <QMessageBox>
#include <algorithm>


//戴代码


BidWindow::BidWindow(UserType type, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::BidWindow),
    userType(type)
{
    ui->setupUi(this);
    
    // 根据用户类型设置标题
    if (type == SUPPLIER) {
        setWindowTitle("供电端 - 竞价提交");
        ui->titleLabel->setText("请输入8组供电价格和电量数据");
    } else {
        setWindowTitle("用户端 - 竞价提交");
        ui->titleLabel->setText("请输入8组购电价格和电量数据");
    }
}

BidWindow::~BidWindow()
{
    delete ui;
}

QVector<PriceQuantity> BidWindow::getSortedData() const
{
    return sortedData;
}

bool BidWindow::collectAndValidateData(QVector<PriceQuantity> &data)
{
    // 从输入框收集数据
    QVector<std::pair<QLineEdit*, QLineEdit*>> dataEdits = {
        {ui->priceEdit1, ui->quantityEdit1},
        {ui->priceEdit2, ui->quantityEdit2},
        {ui->priceEdit3, ui->quantityEdit3},
        {ui->priceEdit4, ui->quantityEdit4},
        {ui->priceEdit5, ui->quantityEdit5},
        {ui->priceEdit6, ui->quantityEdit6},
        {ui->priceEdit7, ui->quantityEdit7},
        {ui->priceEdit8, ui->quantityEdit8}
    };
    
    data.clear();
    for (auto &pair : dataEdits) {
        QLineEdit* priceEdit = pair.first;
        QLineEdit* quantityEdit = pair.second;
        
        QString priceText = priceEdit->text();
        QString quantityText = quantityEdit->text();
        
        bool priceOk, quantityOk;
        double price = priceText.toDouble(&priceOk);
        double quantity = quantityText.toDouble(&quantityOk);
        
        // 验证输入是否有效
        if (!priceOk || !quantityOk || price < 0 || quantity <= 0) {
            ui->messageLabel->setText("请输入有效的非负电价和正电量！");
            return false;
        }
        
        data.append({price, quantity});
    }
    
    ui->messageLabel->setText("");
    return true;
}

void BidWindow::on_submitButton_clicked()
{
    QVector<PriceQuantity> data;
    
    // 收集并验证数据
    if (!collectAndValidateData(data)) {
        return;
    }
    
    // 根据用户类型进行排序
    if (userType == SUPPLIER) {
        // 供电端：按电价递增排序
        std::sort(data.begin(), data.end(), [](const PriceQuantity &a, const PriceQuantity &b) {
            return a.price < b.price;
        });
    } else {
        // 用户端：按电价递减排序
        std::sort(data.begin(), data.end(), [](const PriceQuantity &a, const PriceQuantity &b) {
            return a.price > b.price;
        });
    }
    
    sortedData = data;
    
    // 显示成功消息
    QMessageBox::information(this, "提交成功", "竞价数据已提交！");
    accept();
}
